﻿using System;
using System.Collections.Generic;
using FineUI;
using SDLITS.Common;
using SDLITS.Model;
using System.Configuration;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace SDLITS.Web.Driver
{
    public partial class AllCardManage : CommonBase
    {
        #region Private Field
        public DataSet Ds;
        public enum EnumActionType
        {
            AddDriverCard,
            AddTempCard,
            ModifyDriverCard,
            ModifyTempCard,
            UpdateTempCard
        }

        public static string AppServer = ConfigurationManager.AppSettings["AppServer"];
        public static readonly string IDShotPath = string.Format(@"\\{0}\IDShot\", AppServer);
        public static readonly string FingerShotPath = string.Format(@"\\{0}\FingerShot\", AppServer);
        public static readonly string CamShotPath = string.Format(@"\\{0}\CamShot\", AppServer);


        public static readonly string IDShotPathFinal = @"/Img/IDShot/";
        public static readonly string FingerShotPathFinal = @"/Img/FingerShot/";
        public static readonly string CamShotPathFinal = @"/Img/CamShot/";

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidCamShotTimesnap.Text = DateTime.Now.ToString().Replace(" ", "").Replace("-", "").Replace(":", "").Replace("/", "");
                hidMapPath1.Text = @"/Img/IDShotTemp/";
                hidMapPath1p.Text = string.Format(@"\\{0}\IDShotTemp\", AppServer);
                hidMapPath2.Text = @"/Img/FingerShotTemp/";
                hidMapPath2p.Text = string.Format(@"\\{0}\FingerShotTemp\", AppServer);
                hidMapPath3.Text = @"/Img/CamShotTemp/";
                hidMapPath3p.Text = string.Format(@"\\{0}\CamShotTemp\", AppServer);
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (ViewState["IsRead"] != null)
            {
                ChangeBtnStatus();
            }
        }
        private void BindGrid(DataSet dataSet)
        {
            if (dataSet != null && dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
            {
                Grid1.DataSource = dataSet.Tables[0];
                Grid1.DataBind();
            }
            else
            {
                Grid1.DataSource = null;
                Grid1.DataBind();
            }
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(lblIDNumber.Text))
            {
                Alert.Show("身份证读取失败，请重试");
                imgIDShot.ImageUrl = "../Img/photoTemp.jpg";
                return;
            }
            if (!Methed.CheckCard(lblIDNumber.Text, 3))
            {
                InitAllFields();
                ClearAllStatus();
                ClearControl();
                imgIDShot.ImageUrl = string.Format("{1}{2}/{0}.bmp", lblIDNumber.Text, hidMapPath1.Text, hidIDShotTimesnap.Text);
                ViewState["IsRead"] = true;
                Ds = GetCardInfoDataList();
                BindGrid(Ds);
                if (Ds != null && Ds.Tables.Count > 0 && Ds.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = Ds.Tables[0].Rows[0];
                    string memType = dr["MemType"].ToString();
                    switch (memType)
                    {
                        case "临时卡":
                            lbtnUpdateCard.Visible = true;
                            ViewState["MemTypeID"] = "2";
                            break;
                        default:
                            ViewState["MemTypeID"] = "1";
                            break;
                    }
                    ViewState["MemCardID"] = dr["MemCardID"].ToString();
                    ViewState["MemCardNo"] = dr["MemCardNo"].ToString();

                    txtMemCardNo.Text = dr["MemCardNo"] is DBNull ? "" : dr["MemCardNo"].ToString();
                    lblMemType.Text = memType;
                    txtStartDate.Text = dr["StartDate"] is DBNull ? "" : dr["StartDate"].ToString();
                    lblExpireDate.Text = dr["ExpireDate"] is DBNull ? "" : dr["ExpireDate"].ToString();
                    lblLeftCash.Text = dr["LeftCash"] is DBNull ? "" : dr["LeftCash"].ToString();
                }

                DataSet Ds2 = GetMemberInfoDataList();
                if (Ds2 != null && Ds2.Tables.Count > 0 && Ds2.Tables[0].Rows.Count > 0)
                {
                    DataRow dr = Ds2.Tables[0].Rows[0];

                    txtDLName.Text = dr["DLName"] is DBNull ? "" : dr["DLName"].ToString();
                    rbtnDLSex.SelectedValue = dr["DLSex"].Equals(true) ? "true" : "false";
                    txtDLNumber.Text = dr["DLNumber"] is DBNull ? "" : dr["DLNumber"].ToString();
                    txtDLAddress.Text = dr["DLAddress"] is DBNull ? "" : dr["DLAddress"].ToString();
                    txtCarNo.Text = dr["CarNo"] is DBNull ? "" : dr["CarNo"].ToString();
                    txtCarEnginNo.Text = dr["CarEnginNo"] is DBNull ? "" : dr["CarEnginNo"].ToString();
                    txtCarIDNo.Text = dr["CarIDNo"] is DBNull ? "" : dr["CarIDNo"].ToString();
                    txtCarOwnerName.Text = dr["CarOwnerName"] is DBNull ? "" : dr["CarOwnerName"].ToString();
                    txtCarOwnerAddr.Text = dr["CarOwnerAddr"] is DBNull ? "" : dr["CarOwnerAddr"].ToString();
                    txtGCarNo.Text = dr["GCarNo"] is DBNull ? "" : dr["GCarNo"].ToString();
                    txtGCarIDNo.Text = dr["GCarIDNo"] is DBNull ? "" : dr["GCarIDNo"].ToString();

                    txtCell.Text = dr["Cell"] is DBNull ? "" : dr["Cell"].ToString();
                    txtPhone.Text = dr["Phone"] is DBNull ? "" : dr["Phone"].ToString();
                    txtCustom1.Text = dr["Custom1"] is DBNull ? "" : dr["Custom1"].ToString();
                    txtCustom2.Text = dr["Custom2"] is DBNull ? "" : dr["Custom2"].ToString();

                    ViewState["MemberID"] = Ds2.Tables[0].Rows[0]["MemberID"].ToString();
                    if (!(dr["FingerShot"] is DBNull))
                    {
                        imgFinger.ImageUrl = string.Format("{0}{1}.bmp", FingerShotPathFinal, lblIDNumber.Text);
                    }
                    if (!(dr["CamShot"] is DBNull))
                    {
                        imgCam.ImageUrl = string.Format("{0}{1}.jpg", CamShotPathFinal, lblIDNumber.Text);
                    }
                }
                else
                {
                    ClearControl();
                }
            }
            else
            {
                Alert.Show("读卡失败");
                Response.Redirect("~/SystemManage/CompanyMemberManage.aspx");

            }
        }

        protected void lbtnAddDriverCard_Click(object sender, EventArgs e)
        {
            ViewState["CurrentAction"] = EnumActionType.AddDriverCard;
            ViewState["MemTypeID"] = "1";
        }

        protected void lbtnAddTempCard_Click(object sender, EventArgs e)
        {
            ViewState["CurrentAction"] = EnumActionType.AddTempCard;
            ViewState["MemTypeID"] = "2";
        }

        protected void lbtnModifyCard_Click(object sender, EventArgs e)
        {
            switch (ViewState["MemTypeID"].ToString())
            {
                case "1":
                    ViewState["CurrentAction"] = EnumActionType.ModifyDriverCard;
                    break;
                case "2":
                    ViewState["CurrentAction"] = EnumActionType.ModifyTempCard;
                    break;
            }
        }

        protected void lbtnFreeCard_Click(object sender, EventArgs e)
        {
            int result = 0;
            int mid=Convert.ToInt32(ViewState["MemCardID"]);
            result += SDDbSession.Default.FromSql("UPDATE [MemCard] SET [StatusID] = 3 WHERE [MemCardID]= " +mid ).ExecuteNonQuery();
            result += SDDbSession.Default.FromSql("INSERT INTO [MemCardHistory]([MemberID],[MemCardID],[CreateDate]) VALUES((Select MemberID from MemberInfo where MemCardID=" + mid + ")," + mid + ",'" + DateTime.Now + "')").ExecuteNonQuery();
            result += SDDbSession.Default.FromSql("UPDATE [MemberInfo] SET [MemCardID] = 0 WHERE [MemCardID]= "+mid).ExecuteNonQuery();
            if (result == 0)
            {
                Alert.Show("冻结选中记录时发生错误！请重试！");
                return;
            }
            Alert.Show("冻结选中的卡数据成功", "提示", "window.location.reload()");
        }

        protected void lbtnUpdateCard_Click(object sender, EventArgs e)
        {
            ViewState["CurrentAction"] = EnumActionType.UpdateTempCard;
        }

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            e.Values[3] = Methed.Status(e.Values[3].ToString());
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid(Ds);
        }
        private void ChangeBtnStatus()
        {
            InitAllFields();
            spanDataList.Hidden = false;
            spanIdentity.Hidden = false;
            if (ViewState["CurrentAction"] == null)
            {
                //spanActions.Hidden = false;
                lbtnAddDriverCard.Hidden = false;
                lbtnAddTempCard.Hidden = false;
                lbtnModifyCard.Hidden = false;
                lbtnFreeCard.Hidden = false;
                lbtnUpdateCard.Hidden = false;

                if (ViewState["MemCardID"] == null)
                {
                    lbtnAddDriverCard.Hidden = false;
                    lbtnAddTempCard.Hidden = false;

                    return;
                }
                lbtnModifyCard.Hidden = false;
                lbtnFreeCard.Hidden = false;
                if (ViewState["MemTypeID"].ToString() == "2")
                {
                    lbtnUpdateCard.Hidden = false;
                }
            }
            else
            {
                spanDataList.Hidden = true;
                switch ((EnumActionType)ViewState["CurrentAction"])
                {
                    case EnumActionType.AddTempCard:
                        dataCard.Hidden = false;
                        lbtnSubmitTemp.Hidden = false;
                        break;
                    case EnumActionType.ModifyTempCard:
                        dataCard.Hidden = false;
                        lbtnSubmitTemp.Hidden = false;
                        txtStartDate.Readonly = true;
                        break;
                    case EnumActionType.UpdateTempCard:
                        dataCard.Hidden = false;
                        dataPersonal.Hidden = false;
                        dataDriverCardInfo.Hidden = false;
                        dataRunCardInfo.Hidden = false;
                        txtStartDate.Readonly = true;
                        lbtnSubmitDriver.Hidden = false;
                        break;
                    case EnumActionType.AddDriverCard:
                        dataDriverCardInfo.Hidden = false;
                        dataRunCardInfo.Hidden = false;
                        dataCard.Hidden = false;
                        dataPersonal.Hidden = false;
                        lbtnSubmitDriver.Hidden = false;
                        break;
                    case EnumActionType.ModifyDriverCard:
                        dataDriverCardInfo.Hidden = false;
                        dataRunCardInfo.Hidden = false;
                        dataCard.Hidden = false;
                        dataPersonal.Hidden = false;
                        txtStartDate.Readonly = true;
                        lbtnSubmitDriver.Hidden = false;
                        break;
                }
                lbtnSubmitDriver.Hidden = false;
                lbtnSubmitTemp.Hidden = false;
            }
        }
        private void InitAllFields()
        {
            if (File.Exists(string.Format("{0}{1}{2}.bmp", hidMapPath2p.Text, lblIDNumber.Text, hidFingerShotTimesnap.Text)))
            {
                imgFinger.ImageUrl = string.Format("{0}{1}{2}.bmp", hidMapPath2.Text, lblIDNumber.Text, hidFingerShotTimesnap.Text);
            }

            if (File.Exists(string.Format("{0}{1}{2}.jpg", hidMapPath3p.Text, lblIDNumber.Text, hidCamShotTimesnap.Text)))
            {
                imgCam.ImageUrl = string.Format("{0}{1}{2}.jpg", hidMapPath3.Text, lblIDNumber.Text, hidCamShotTimesnap.Text);
            }

            spanActions.Hidden = true;

            spanIdentity.Hidden = false;
            spanDataList.Hidden = true;
            dataCard.Hidden = true;
            dataDriverCardInfo.Hidden = true;
            dataRunCardInfo.Hidden = true;
            dataPersonal.Hidden = true;

            lbtnAddDriverCard.Hidden = true;
            lbtnAddTempCard.Hidden = true;
            lbtnFreeCard.Hidden = true;
            lbtnModifyCard.Hidden = true;
            lbtnSubmitDriver.Hidden = true;
            lbtnSubmitTemp.Hidden = true;
            lbtnSubmitTemp.Hidden = true;

            txtStartDate.Text = DateTime.Now.ToShortDateString();
        }
        private void ClearAllStatus()
        {
            ViewState["IsRead"] = null;
            ViewState["MemberID"] = null;
            ViewState["MemTypeID"] = null;
            ViewState["MemCardID"] = null;
            ViewState["MemCardNo"] = null;
            ViewState["CurrentAction"] = null;
        }

        private void ClearControl()
        {
            txtPhone.Text = "";
            txtCell.Text = "";

            txtMemCardNo.Text = "";
            lblMemType.Text = "";
            txtStartDate.Text = DateTime.Now.ToShortDateString();
            lblExpireDate.Text = "";
            lblLeftCash.Text = "";

            txtDLName.Text = "";
            txtDLNumber.Text = "";
            txtDLAddress.Text = "";

            txtCarNo.Text = "";
            txtCarEnginNo.Text = "";
            txtCarIDNo.Text = "";
            txtCarOwnerName.Text = "";
            txtCarOwnerAddr.Text = "";
            txtGCarIDNo.Text = "";
            txtGCarNo.Text = "";
        }
        private DataSet GetCardInfoDataList()
        {
            SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@IDNumber",lblIDNumber.Text),
                    new SqlParameter("@SPAction","SelectCardInfoByIDNumber")
                };
            return SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp).ToDataSet();
        }
        private DataSet GetMemberInfoDataList()
        {
            SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@IDNumber",lblIDNumber.Text),
                    new SqlParameter("@SPAction","SelectMemberInfoByIDNumber")
                };
            return SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp).ToDataSet();
        }
        protected void lbtnSubmitTemp_Click(object sender, EventArgs e)
        {
            string initialAmount = GetInitialAmount();
            string workAmount = GetWorkAmount();
            switch ((EnumActionType)ViewState["CurrentAction"])
            {
                case EnumActionType.AddTempCard:
                    if (AddCardInfo())
                    {
                        RechargeInit(initialAmount, "0");
                        Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}", txtMemCardNo.Text.Trim(), initialAmount));
                        return;
                    }
                    Alert.Show("临时卡添加失败！临时卡已存在!");
                    break;
                case EnumActionType.ModifyTempCard:
                    if (ModifyCardInfo())
                    {
                        if (ViewState["MemCardNo"].ToString().Equals(txtMemCardNo.Text.Trim()))
                        {
                            Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}", txtMemCardNo.Text.Trim(), "0"));
                        }
                        else
                        {
                            AddCardHistory(ViewState["MemCardNo"].ToString());
                            RechargeInit(initialAmount, workAmount);
                            Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}&work={2}", txtMemCardNo.Text.Trim(), initialAmount, workAmount));
                        }

                        return;
                    }
                    Alert.Show("出错了", "临时卡更新失败！临时卡已存在!");
                    break;
            }
        }
        protected void lbtnSubmitDriver_Click(object sender, EventArgs e)
        {
            string initialAmount = GetInitialAmount();
            string workAmount = GetWorkAmount();
            switch ((EnumActionType)ViewState["CurrentAction"])
            {
                case EnumActionType.AddDriverCard:
                    if (AddCardInfo())
                    {
                        RechargeInit(initialAmount, "0");
                        Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}", txtMemCardNo.Text.Trim(), initialAmount));
                        return;
                    }
                    Alert.Show("驾驶员出入卡添加失败！驾驶员卡已存在!");
                    break;
                case EnumActionType.ModifyDriverCard:
                    if (ModifyCardInfo())
                    {
                        if (ViewState["MemCardNo"].ToString().Equals(txtMemCardNo.Text.Trim()))
                        {
                            Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}", txtMemCardNo.Text.Trim(), "0"));
                        }
                        else
                        {
                            AddCardHistory(ViewState["MemCardNo"].ToString());
                            RechargeInit(initialAmount, workAmount);
                            Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}&work={2}", txtMemCardNo.Text.Trim(), initialAmount, workAmount));
                        }
                        return;
                    }
                    Alert.Show("驾驶员出入卡更新失败！驾驶员卡已存在!");
                    break;
                case EnumActionType.UpdateTempCard:
                    if (UpdateCardInfo())
                    {
                        RechargeInit(initialAmount, "0");
                        Response.Redirect(string.Format("CardRechargeManage.aspx?cardNO={0}&init={1}", txtMemCardNo.Text.Trim(), initialAmount));
                        return;
                    }
                    Alert.Show ( "临时卡升级失败！临时卡已存在!");
                    break;
            }
        }
        public string GetInitialAmount()
        {
            MasterDic md = SDDbSession.Default.From<MasterDic>().ToFirst();
            if (md!=null)
            {
                return md.InitialAmount.ToString();
            }
            return "0";
        }
        public string GetWorkAmount()
        {
            MasterDic md = SDDbSession.Default.From<MasterDic>().ToFirst();
            if (md != null)
            {
                return md.WorkAmount.ToString();
            }
            return "0";
        }

        #region Member Card
        private bool AddCardInfo()
        {
            string startDate = txtStartDate.Text.Trim();
            if (string.IsNullOrEmpty(startDate))
            {
                startDate = DateTime.Now.ToShortDateString();
            }
            SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@MemCardNo",txtMemCardNo.Text),
                    new SqlParameter("@StatusID",1),
                    new SqlParameter("@CompanyID",-1),
                    new SqlParameter("@StartDate",Convert.ToDateTime(startDate)),
                    new SqlParameter("@ExpireDate",Convert.ToDateTime(startDate)),
                    new SqlParameter("@MemTypeID",Convert.ToInt32(ViewState["MemTypeID"])),
                    new SqlParameter("@SPAction","Insert")
                };
            object o = SDDbSession.Default.FromProc("TableMemCard").AddParameter(sp).ToScalar();//.ExecuteNonQuery();
            int newID = int.Parse(o.ToString());
            if (newID < 1)
            {
                return false;
            }
            ViewState["MemCardID"] = newID;
            lblExpireDate.Text = startDate;

            string birthday = lblBirthday.Text.Trim();
            if (string.IsNullOrEmpty(birthday))
            {
                birthday = "1900-01-01";
            }
            SqlParameter[] sp2 = new SqlParameter[]{
                    new SqlParameter("@RegistID",GetRegistID()),
                    new SqlParameter("@Name",lblName.Text.Trim()),
                    new SqlParameter("@Sex",Convert.ToBoolean(lblSex.Text.Equals("男"))),
                    new SqlParameter("@Birthday",Convert.ToDateTime(birthday)),
                    new SqlParameter("@IDNumber",lblIDNumber.Text.Trim()),
                    new SqlParameter("@IDAddress",lblIDAddress.Text.Trim()),
                    new SqlParameter("@Cell",txtCell.Text.Trim()),
                    new SqlParameter("@Phone",txtPhone.Text.Trim()),
                    new SqlParameter("@DLName",txtDLName.Text.Trim()),
                    new SqlParameter("@DLSex",Convert.ToBoolean(rbtnDLSex.SelectedValue)),
                    new SqlParameter("@DLNumber",txtDLNumber.Text.Trim()),
                    new SqlParameter("@DLAddress",txtDLAddress.Text.Trim()),
                    new SqlParameter("@CarNo",txtCarNo.Text.Trim()),
                    new SqlParameter("@CarEnginNo",txtCarEnginNo.Text.Trim()),
                    new SqlParameter("@CarIDNo",txtCarIDNo.Text.Trim()),
                    new SqlParameter("@CarOwnerName",txtCarOwnerName.Text.Trim()),
                    new SqlParameter("@CarOwnerAddr",txtCarOwnerAddr.Text.Trim()),
                    new SqlParameter("@GCarNo",txtGCarNo.Text.Trim()),
                    new SqlParameter("@GCarIDNo",txtGCarIDNo.Text.Trim()),
                    new SqlParameter("@MemCardID",newID),
                    new SqlParameter("@IDShot",string.Format("{0}{1}.bmp", IDShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@FingerShot",string.Format("{0}{1}.bmp", FingerShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@CamShot",string.Format("{0}{1}.jpg", CamShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@Custom1",txtCustom1.Text.Trim()),
                    new SqlParameter("@Custom2",txtCustom2.Text.Trim()),
                    new SqlParameter("@SPAction","Insert")
                };
            int result = int.Parse(SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp2).ToScalar().ToString());//.ExecuteNonQuery();
            if (result>0)
            {
                SqlParameter[] sp3 = new SqlParameter[]{
                    new SqlParameter("@IDNumber",lblIDNumber.Text.Trim()),
                    new SqlParameter("@Name",lblName.Text.Trim()),
                    new SqlParameter("@Sex",Convert.ToBoolean(lblSex.Text.Equals("男"))),
                    new SqlParameter("@Birthday",Convert.ToDateTime(birthday)),
                    new SqlParameter("@IDAddress",lblIDAddress.Text.Trim()),
                    new SqlParameter("@MemberID",Convert.ToInt32(ViewState["MemberID"])),
                    new SqlParameter("@Cell",txtCell.Text.Trim()),
                    new SqlParameter("@Phone",txtPhone.Text.Trim()),
                    new SqlParameter("@DLName",txtDLName.Text.Trim()),
                    new SqlParameter("@DLSex",Convert.ToBoolean(rbtnDLSex.SelectedValue)),
                    new SqlParameter("@DLNumber",txtDLNumber.Text.Trim()),
                    new SqlParameter("@DLAddress",txtDLAddress.Text.Trim()),
                    new SqlParameter("@CarNo",txtCarNo.Text.Trim()),
                    new SqlParameter("@CarEnginNo",txtCarEnginNo.Text.Trim()),
                    new SqlParameter("@CarIDNo",txtCarIDNo.Text.Trim()),
                    new SqlParameter("@CarOwnerName",txtCarOwnerName.Text.Trim()),
                    new SqlParameter("@CarOwnerAddr",txtCarOwnerAddr.Text.Trim()),
                    new SqlParameter("@GCarNo",txtGCarNo.Text.Trim()),
                    new SqlParameter("@GCarIDNo",txtGCarIDNo.Text.Trim()),
                    new SqlParameter("@MemCardID",newID),
                    new SqlParameter("@IDShot",string.Format("{0}{1}.bmp", IDShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@FingerShot",string.Format("{0}{1}.bmp", FingerShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@CamShot",string.Format("{0}{1}.jpg", CamShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@Custom1",txtCustom1.Text.Trim()),
                    new SqlParameter("@Custom2",txtCustom2.Text.Trim()),
                    new SqlParameter("@SPAction","UpdateByIDNumber")
                };
                SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp3).ExecuteNonQuery();
                //if (result2<1)
                //{
                //    return false;
                //}
            }

            //MovePhoto();
            return true;
        }

        private bool UpdateCardInfo()
        {
            MemCard mc = new MemCard();
            mc.Attach();
            mc.MemCardID = Convert.ToInt32(ViewState["MemCardID"]);
            mc.MemCardNo = txtMemCardNo.Text;
            mc.MemTypeID = 1;
            int result1=SDDbSession.Default.Update(mc);
            if (result1 < 1)
            {
                return false;
            }

            string birthday = lblBirthday.Text.Trim();
            if (string.IsNullOrEmpty(birthday))
            {
                birthday = "1900-01-01";
            }
            SqlParameter[] sp3 = new SqlParameter[]{
                    new SqlParameter("@IDNumber",lblIDNumber.Text.Trim()),
                    new SqlParameter("@Name",lblName.Text.Trim()),
                    new SqlParameter("@Sex",Convert.ToBoolean(lblSex.Text.Equals("男"))),
                    new SqlParameter("@Birthday",Convert.ToDateTime(birthday)),
                    new SqlParameter("@IDAddress",lblIDAddress.Text.Trim()),
                    new SqlParameter("@MemberID",Convert.ToInt32(ViewState["MemberID"])),
                    new SqlParameter("@Cell",txtCell.Text.Trim()),
                    new SqlParameter("@Phone",txtPhone.Text.Trim()),
                    new SqlParameter("@DLName",txtDLName.Text.Trim()),
                    new SqlParameter("@DLSex",Convert.ToBoolean(rbtnDLSex.SelectedValue)),
                    new SqlParameter("@DLNumber",txtDLNumber.Text.Trim()),
                    new SqlParameter("@DLAddress",txtDLAddress.Text.Trim()),
                    new SqlParameter("@CarNo",txtCarNo.Text.Trim()),
                    new SqlParameter("@CarEnginNo",txtCarEnginNo.Text.Trim()),
                    new SqlParameter("@CarIDNo",txtCarIDNo.Text.Trim()),
                    new SqlParameter("@CarOwnerName",txtCarOwnerName.Text.Trim()),
                    new SqlParameter("@CarOwnerAddr",txtCarOwnerAddr.Text.Trim()),
                    new SqlParameter("@GCarNo",txtGCarNo.Text.Trim()),
                    new SqlParameter("@GCarIDNo",txtGCarIDNo.Text.Trim()),
                    new SqlParameter("@MemCardID", Convert.ToInt32(ViewState["MemCardID"])),
                    new SqlParameter("@IDShot",string.Format("{0}{1}.bmp", IDShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@FingerShot",string.Format("{0}{1}.bmp", FingerShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@CamShot",string.Format("{0}{1}.jpg", CamShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@Custom1",txtCustom1.Text.Trim()),
                    new SqlParameter("@Custom2",txtCustom2.Text.Trim()),
                    new SqlParameter("@SPAction","UpdateByIDNumber")
                };
            SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp3).ExecuteNonQuery();
            //if (result2 < 1)
            //{
            //    return false;
            //}

            //MovePhoto();
            return true;
        }

        private bool ModifyCardInfo()
        {
            MemCard mc = new MemCard();
            mc.Attach();
            mc.MemCardID = Convert.ToInt32(ViewState["MemCardID"]);
            mc.MemCardNo = txtMemCardNo.Text;
            mc.MemTypeID = Convert.ToInt32(ViewState["MemTypeID"]);
            int result1 = SDDbSession.Default.Update(mc);
            if (result1 < 1)
            {
                return false;
            }

            string birthday = lblBirthday.Text.Trim();
            if (string.IsNullOrEmpty(birthday))
            {
                birthday = "1900-01-01";
            }
            SqlParameter[] sp3 = new SqlParameter[]{
                    new SqlParameter("@IDNumber",lblIDNumber.Text.Trim()),
                    new SqlParameter("@Name",lblName.Text.Trim()),
                    new SqlParameter("@Sex",Convert.ToBoolean(lblSex.Text.Equals("男"))),
                    new SqlParameter("@Birthday",Convert.ToDateTime(birthday)),
                    new SqlParameter("@IDAddress",lblIDAddress.Text.Trim()),
                    new SqlParameter("@MemberID",Convert.ToInt32(ViewState["MemberID"])),
                    new SqlParameter("@Cell",txtCell.Text.Trim()),
                    new SqlParameter("@Phone",txtPhone.Text.Trim()),
                    new SqlParameter("@DLName",txtDLName.Text.Trim()),
                    new SqlParameter("@DLSex",Convert.ToBoolean(rbtnDLSex.SelectedValue)),
                    new SqlParameter("@DLNumber",txtDLNumber.Text.Trim()),
                    new SqlParameter("@DLAddress",txtDLAddress.Text.Trim()),
                    new SqlParameter("@CarNo",txtCarNo.Text.Trim()),
                    new SqlParameter("@CarEnginNo",txtCarEnginNo.Text.Trim()),
                    new SqlParameter("@CarIDNo",txtCarIDNo.Text.Trim()),
                    new SqlParameter("@CarOwnerName",txtCarOwnerName.Text.Trim()),
                    new SqlParameter("@CarOwnerAddr",txtCarOwnerAddr.Text.Trim()),
                    new SqlParameter("@GCarNo",txtGCarNo.Text.Trim()),
                    new SqlParameter("@GCarIDNo",txtGCarIDNo.Text.Trim()),
                    new SqlParameter("@FingerShot",string.Format("{0}{1}.bmp", FingerShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@CamShot",string.Format("{0}{1}.jpg", CamShotPathFinal, lblIDNumber.Text)),
                    new SqlParameter("@Custom1",txtCustom1.Text.Trim()),
                    new SqlParameter("@Custom2",txtCustom2.Text.Trim()),
                    new SqlParameter("@MemCardID",Convert.ToInt32(ViewState["MemCardID"])),
                    new SqlParameter("@SPAction","UpdateByIDNumber")
                };
            SDDbSession.Default.FromProc("TableMemberInfo").AddParameter(sp3).ExecuteNonQuery();
            //if (result2 < 1)
            //{
            //    return false;
            //}
            //MovePhoto();
            return true;
        }

        private void MovePhoto()
        {
            try
            {
                if (
                File.Exists(string.Format("{0}{1}\\{2}.bmp", hidMapPath1p.Text, hidIDShotTimesnap.Text, lblIDNumber.Text)))
                {
                    File.Copy(
                        string.Format("{0}{1}\\{2}.bmp", hidMapPath1p.Text, hidIDShotTimesnap.Text, lblIDNumber.Text),
                        string.Format("{0}{1}.bmp", IDShotPath, lblIDNumber.Text), true);
                }

                if (!string.IsNullOrEmpty(hidFingerShotName.Text))
                {
                    File.Copy(
                        string.Format("{0}{1}{2}.bmp", hidMapPath2p.Text, lblIDNumber.Text, hidFingerShotTimesnap.Text),
                        string.Format("{0}{1}.bmp", FingerShotPath, lblIDNumber.Text), true);
                }

                if (!string.IsNullOrEmpty(hidCamShotName.Text))
                {
                    File.Copy(
                        string.Format("{0}{1}{2}.jpg", hidMapPath3p.Text, lblIDNumber.Text, hidCamShotTimesnap.Text),
                        string.Format("{0}{1}.jpg", CamShotPath, lblIDNumber.Text), true);
                }
            }
            catch (Exception e)
            {
                ReadAndAppendFile(Server.MapPath("~/error.log"), string.Format("{0}  -  {1}  \r\n", DateTime.Now, e.Message));
            }
        }
        public static void ReadAndAppendFile(string filePath, string content)
        {
            File.AppendAllText(filePath, content, Encoding.GetEncoding("utf-8"));
        }
        #endregion

        private void RechargeInit(string initialAmount, string workAmount)
        {
            ModelLoginUser user = (ModelLoginUser)Session["LoginUser"];
            if (user == null)
            {
                var cr = new CardReset();
                DoCardReset(txtMemCardNo.Text.Trim());
            }
            else
            {
                DateTime expireDate = DateTime.Now;
                if (!string.IsNullOrEmpty(lblExpireDate.Text))
                {
                    expireDate = Convert.ToDateTime(lblExpireDate.Text);
                }
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@InitialAmount",Convert.ToDecimal(initialAmount)),
                    new SqlParameter("@WorkAmount",Convert.ToDecimal(workAmount)),
                    new SqlParameter("@BonusAmount",0),
                    new SqlParameter("@PlusDays",Convert.ToInt32(expireDate.Subtract(DateTime.Today).Days)),
                    new SqlParameter("@PlusTimes",0),
                    new SqlParameter("@PlusAmount",0),
                    new SqlParameter("@CreateUserID",user.UserID),
                    new SqlParameter("@MemcardNo",txtMemCardNo.Text.Trim()),
                    new SqlParameter("@PlusDays2Log",0),
                    new SqlParameter("@SPAction","Recharge")
                };
                SDDbSession.Default.FromProc("TableCardRevenue").AddParameter(sp).ExecuteNonQuery();
                //if (ds<1)
                //{
                //    Alert.Show("办卡失败，请返回重试！");

                //    return;
                //}
            }
        }
        public bool DoCardReset(string cardNo)
        {
            SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@MemCardNo",cardNo),
                    new SqlParameter("@SPAction","ResetCard")
                };
            SDDbSession.Default.FromProc("TableMemCard").AddParameter(sp).ExecuteNonQuery();
            //if (ds<1)
            //{
            //    return false;
            //}
            return true;
        }
        private void AddCardHistory(string oldMemCardNo)
        {
            MemCardHistory mch = new MemCardHistory();
            mch.DeAttach();
            mch.MemberID = Convert.ToInt32(ViewState["MemberID"]);
            mch.MemCardNo = oldMemCardNo;
            mch.CreateDate = DateTime.Now;
            SDDbSession.Default.Insert(mch);
        }

        public string GetRegistID()
        {
            int count= SDDbSession.Default.From<MemberInfo>().Count();
            if (count<1)
            {
                return "DJ00000001";
            }
            MemberInfo oldRegistID = SDDbSession.Default.From<MemberInfo>().OrderBy(MemberInfo._.MemberID.Desc).ToFirst();
            string newSerial = oldRegistID.RegistID.Substring(2).TrimStart('0');
            string newRegistID = String.Format("DJ{0}", (Convert.ToInt32(newSerial) + 1).ToString().PadLeft(8, '0'));
            return newRegistID;
        }

        protected void file_upload_FileSelected(object sender, EventArgs e)
        {
            if (file_upload.HasFile)
            {
                string fileName = file_upload.ShortFileName;
                string exName=fileName.Substring(fileName.IndexOf('.')+1).Trim().ToLower();
                if (exName != "jpg")
                {
                    Alert.Show("只支持jpg图片");
                    return;
                }

                string server = ConfigurationManager.AppSettings["AppServer"];
                //string sDirectory = string.Format(@"\\{0}\CamShotTemp\", server);
                string sDirectory = Server.MapPath("~/Img/CamShot/");
                if (!Directory.Exists(sDirectory))
                    Directory.CreateDirectory(sDirectory);

                file_upload.SaveAs(Path.Combine(sDirectory, lblIDNumber.Text + ".jpg"));
                //imgCam.ImageUrl = Path.Combine(sDirectory, lblIDNumber.Text + hidCamShotTimesnap.Text + ".jpg");
                imgCam.ImageUrl = Path.Combine("/Img/CamShot/", lblIDNumber.Text + ".jpg");
                file_upload.Reset();

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("AllCardManage.aspx");
        }
    }
}